﻿
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using bpms.Models;
using MySql.Data.MySqlClient;

namespace bpms.Dao
{
    /// <summary>
    /// 数据库备份Log持久层
    /// </summary>
    public class BackupDBLogDao
    {
        public List<BackupDBLog> GetAll(string backupdir)
        {
            List<BackupDBLog> backupLogs = Directory.GetFiles(backupdir)
                .Where(file => Path.GetFileName(file).StartsWith("mysql_backup_"))
                .Select(file => new FileInfo(file))
                .OrderByDescending(f => f.CreationTime)
                .Select(f => new BackupDBLog { FilePath = f.FullName, CreatedTime = f.CreationTime })
                .ToList();
            return backupLogs;
        }

        public void BackupMySqlDatabase(string server, string database, string userId,
            string password, string backupFilePath, int type, string mysqldumpPath)
        {
            //string mysqldumpPath = @"C:\Program Files\MySQL\MySQL Server 8.0\bin\mysqldump.exe";
            ProcessStartInfo psi = new ProcessStartInfo
            {
                FileName = mysqldumpPath,
                Arguments = $"--host={server} --user={userId} --password={password} --single-transaction --routines --triggers --databases {database} --result-file=\"{backupFilePath}\"",
                RedirectStandardInput = false,
                RedirectStandardOutput = false,
                UseShellExecute = false,
                CreateNoWindow = true
            };

            using (Process process = new Process())
            {
                process.StartInfo = psi;
                process.Start();
                process.WaitForExit();
            }
        }

        public void RestoreMySqlDatabase(string server, string database, string userId, string password,
      string backupFilePath, string mysqlexePath)
        {
            // 1. 使用8.3短文件名格式避免空格问题
            string shortMysqlPath = GetShortPathName(mysqlexePath);
            string shortBackupPath = GetShortPathName(backupFilePath);

            // 2. 构建完整的CMD命令
            string args = $"/c \"\"{shortMysqlPath}\" --host={server} --user={userId} --password={password} {database} < \"{shortBackupPath}\"\"";

            var psi = new ProcessStartInfo
            {
                FileName = "cmd.exe",
                Arguments = args,
                UseShellExecute = false,
                CreateNoWindow = true,
                RedirectStandardError = true,
                RedirectStandardOutput = true
            };

            using (var process = new Process())
            {
                process.StartInfo = psi;
                process.Start();

                string output = process.StandardOutput.ReadToEnd();
                string errors = process.StandardError.ReadToEnd();

                process.WaitForExit();

                if (process.ExitCode != 0)
                {
                    throw new Exception($"(代码:{process.ExitCode}): {errors}{Environment.NewLine}输出: {output}");
                }
            }
        }

        // 获取8.3格式短路径
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        private static extern int GetShortPathName(
            [MarshalAs(UnmanagedType.LPTStr)] string path,
            [MarshalAs(UnmanagedType.LPTStr)] StringBuilder shortPath,
            int bufferSize);

        public static string GetShortPathName(string longPath)
        {
            StringBuilder shortPath = new StringBuilder(255);
            GetShortPathName(longPath, shortPath, shortPath.Capacity);
            return shortPath.ToString();
        }
    }
}
